layui.config({
    base: '../authtree/extends/',
}).extend({
    authtree: 'authtree',
});

var userId;
var $
layui.use(['jquery', 'authtree', 'form', 'layer'], function () {
    userId = top.userId;
    $ = layui.jquery;
    layer = layui.layer;
    var authtree = layui.authtree;
    var form = layui.form;

    // 初始化用户权限树
    $.ajax({
        url: '/admin/authtree?userId=' + userId,
        dataType: 'json',
        success: function (data) {
            if (data.code == 0) {
                // 渲染时传入渲染目标ID，树形结构数据（具体结构看样例，checked表示默认选中），以及input表单的名字
                authtree.render('#LAY-auth-tree-index', data.data, {
                    inputname: 'authids[]',
                    layfilter: 'lay-check-auth',
                    autowidth: true,
                });

                // 监听自定义lay-filter选中状态，PS:layui现在不支持多次监听，所以扩展里边只能改变触发逻辑，然后引起了事件冒泡延迟的BUG，要是谁有好的建议可以反馈我
                form.on('checkbox(lay-check-auth)', function (data) {
                    // 注意这里：需要等待事件冒泡完成，不然获取叶子节点不准确。
                    setTimeout(function () {
                        // 获取所有节点
                        var all = authtree.getAll('#LAY-auth-tree-index');
                        console.log('all', all);
                        // 获取所有已选中节点
                        var checked = authtree.getChecked('#LAY-auth-tree-index');
                        console.log('checked', checked);
                        // 获取所有未选中节点
                        var notchecked = authtree.getNotChecked('#LAY-auth-tree-index');
                        console.log('notchecked', notchecked);
                        // 获取选中的叶子节点
                        var leaf = authtree.getLeaf('#LAY-auth-tree-index');
                        console.log('leaf', leaf);
                    }, 100);
                });
            }
        }
    });
    form.on('submit(LAY-auth-tree-submit)', function (obj) {
        var authids = authtree.getChecked('#LAY-auth-tree-index').remove("undefined").join(",");
        console.log('Choosed authids is', authids);
        $.ajax({
            url: '/admin/modifyAuth',
            dataType: 'json',
            data: {"userId": userId, "authIds": authids},
            success: function (res) {
                if (res.code == 0) {
                    layer.msg('修改权限成功');
                }
            }
        });
        return false;
    });

    //加载用户的ip白名单列表
    $.ajax({
        url: '/admin/getIPList'
        , dataType: 'json'
        , data: {
            "userId": userId
        }
        , success: function (res) {
            if (res.code == 0) {
                var ips = res.data.ips;
                $('#ips').val(ips.trim().length == 0 ? null : ips);
            }
        }
    });
});


function refreshAccessSecret() {
    var index = parent.layer.load(1, {
        shade: [0.3, '#000']
    });
    $.ajax({
        url: '/admin/refresh',
        dataType: 'json',
        data: {
            "accessSecret": "1",
            "accessKey": $('#accessKey').val(),
            "userName": $('#userName').val(),
            "id": $('#userId').val()
        },
        success: function (res) {
            if (res.code == 0) {
                parent.layer.close(index);
                $('#accessSecret').val(res.data.accessSecret);
            }
        }
    });
}

function refreshSignToken() {
    var index = parent.layer.load(1, {
        shade: [0.3, '#000']
    });
    $.ajax({
        url: '/admin/refresh',
        dataType: 'json',
        data: {
            "signToken": "1",
            "accessKey": $('#accessKey').val(),
            "userName": $('#userName').val(),
            "id": $('#userId').val()
        },
        success: function (res) {
            if (res.code == 0) {
                parent.layer.close(index);
                $('#signToken').val(res.data.signToken);
            }
        }
    });
}

function updateIps() {
    var index = parent.layer.load(1, {
        shade: [0.3, '#000']
    });
    var ips = $('#ips').val();
    if (ips.trim().length == 0) {
        ips = null;
    }
    $.ajax({
        url: '/admin/refresh'
        , dataType: 'json'
        , data: {
            "id": userId,
            "userName":$('#userName').val(),
            "ipWhilteList": ips
        }
        , success: function (res) {
            if (res.code == 0) {
                $('#ips').val(res.data.ips);
                parent.layer.msg('修改成功', {icon: 1});
            }else{
                parent.layer.msg(res.msg, {icon: 2});
            }
        },complete:function(res){
            parent.layer.close(index);
        }
    });
}

Array.prototype.indexOf = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};

Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
    return this;
};